package net.cassandraview.dbnav;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import javax.swing.tree.TreeNode;

public class NavigationNode implements TreeNode {

	protected String name;
	
	protected List<TreeNode> children = new ArrayList<TreeNode>();
	
	protected NavigationNodeType type;
	
	protected TreeNode parent;
	
	protected boolean leaf = false;
	
	public NavigationNode() {
		this("", NavigationNodeType.UNKNOWN, false);
	}
	
	public NavigationNode(String name, NavigationNodeType type, boolean leaf) {
		this.name = name;
		this.type = type;
		this.leaf = leaf;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public NavigationNodeType getType() {
		return type;
	}

	public void setType(NavigationNodeType type) {
		this.type = type;
	}

	public void setParent(TreeNode parent) {
		this.parent = parent;
	}

	public String getKeyspace() {
		if (type == null || type.equals(NavigationNodeType.UNKNOWN))
			return null;
		if (type != null && type.equals(NavigationNodeType.KEYSPACE)) {
			return name;
		} else {
			try {
				NavigationNode parent = (NavigationNode) getParent();
				do {
					if (parent == null)
						return null;
					if (parent.type == null)
						return null;
					if (parent.type.equals(NavigationNodeType.KEYSPACE)) {
						return parent.name;
					} else {
						parent = (NavigationNode) parent.getParent();
					}
				} while(true);
			} catch (ClassCastException e) {
				//TODO: maybe there is a better solution, but...
				return null;
			}
		}
	}
	
	public void addChildren(Collection<TreeNode> children) {
		if (!leaf) {
			this.children.addAll(children);
		}
	}
	
	public void addChild(TreeNode child) {
		if (!leaf) {
			this.children.add(child);
		}
	}
	
	@Override
	public TreeNode getChildAt(int childIndex) {
		if (!leaf) {
			return children.get(childIndex);
		} else {
			return null;
		}
	}

	@Override
	public int getChildCount() {
		if (!leaf) {
			return children.size();
		} else {
			return 0;
		}
	}

	@Override
	public TreeNode getParent() {
		return parent;
	}

	@Override
	public int getIndex(TreeNode node) {
		if (!leaf) {
			return children.indexOf(node);
		} else {
			return 0;
		}
	}

	@Override
	public boolean getAllowsChildren() {
		return !leaf;
	}

	@Override
	public boolean isLeaf() {
		return leaf;
	}
	
	public void setLeaf(boolean leaf) {
		this.leaf = leaf;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Enumeration children() {
		return Collections.enumeration(children);
	}

	@Override
	public String toString() {
		return "NavigationNode [name=" + name + ", type=" + type + "]";
	}

}
